﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Kiiro.Common.Utility;
using Kiiro.Common.Entities;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.MasterPage;
using Kiiro.Model;
using Kiiro.SiteDefinition.Core;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.HtmlControls;
using System.Web;

namespace Kiiro.SiteDefinition.PortalPages
{
    public partial class ClosedProjects : BasePage
    {
        public Pager V2Pager
        {
            get { return ( Pager ) v2Pager; }
        }

        public WelcomeMessagePanel V2WelcomeMessagePanel
        {
            get { return ( WelcomeMessagePanel ) v2WelcomeMessagePanel; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public Filter Filter
        {
            get { return ( Filter ) v2Filter; }
        }

        private List<Project> projects = new List<Project> ( );
        public List<Project> Projects
        {
            get { return projects; }
            set { projects = value; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            litTitle.Text = "Closed Projects";

            AddCommandButtons ( );

            if ( PermissionBitsProjects [ 1 ] )
            {
                V2Pager.NextClick += new EventHandler ( RePopulatePage );
                V2Pager.PrevClick += new EventHandler ( RePopulatePage );
                V2Pager.EntitiesPerPageChange += new EventHandler ( RePopulatePage );

                Projects = ProjectsModel.GetProjectsForUser ( SiteCollectionId, ServerRelativeUrl, CurrentUser, new List<ProjectStatus> ( ) { ProjectStatus.Closed } );
                Projects.ForEach ( x => x.CustomFieldNamesAndValues = CustomModel.HarvestCustomFields ( typeof ( Project ), x.Id, HttpContext.Current, SiteCollectionId, ServerRelativeUrl ) );

                Filter.EntityType = EntityType.Project;
                Filter.Entities = Projects.Cast<BaseEntity> ( ).ToList ( );
                Projects = Filter.Apply ( ).Cast<Project> ( ).ToList ( );

                PopulatePage ( );
            }
            else
            {
                actionBar.Visible = false;
                v2WelcomeMessagePanel.Visible = true;
                V2WelcomeMessagePanel.ShowPanel = true;
                V2WelcomeMessagePanel.ServerRelativeUrl = ServerRelativeUrl;
                V2WelcomeMessagePanel.ManageUsers = false;
                V2WelcomeMessagePanel.ShowHidePanel ( Constants.PagerEntity.Projects, PermissionBitsProjects );
                columnHeaders.Visible = false;
                v2Pager.Visible = false;
            }
        }

        #region Page Related Methods

        internal void PopulatePage ( )
        {
            if ( Projects.Count > 0 || !string.IsNullOrEmpty ( Request.Params [ "Field" ] ) )
            {
                //sorts the list based on expression and direction
                SortList ( );

                V2Pager.PopulatePager ( projects.Count, Constants.PagerEntity.Projects );

                rptProject.DataSource = projects.GetRange ( V2Pager.PagingIndex, V2Pager.DisplayedCount );
                rptProject.DataBind ( );

                if ( rptProject.Items.Count > 0 )
                {
                    HtmlTableRow trProject = ( HtmlTableRow ) rptProject.Items [ rptProject.Items.Count - 1 ].FindControl ( "trProject" );
                    trProject.Attributes.Add ( "class", "borderless" );
                }
            }
            else
            {
                actionBar.Visible = false;
                v2Pager.Visible = false;
                columnHeaders.Visible = false;
                v2WelcomeMessagePanel.Visible = true;
                V2WelcomeMessagePanel.ShowPanel = true;
                V2WelcomeMessagePanel.ServerRelativeUrl = ServerRelativeUrl;
                V2WelcomeMessagePanel.ManageUsers = PermissionBitsUsers [ 0 ];
                V2WelcomeMessagePanel.ShowHidePanel ( Constants.PagerEntity.Projects, PermissionBitsProjects );

            }
        }

        private void AddCommandButtons ( )
        {
            if ( PermissionBitsProjects [ 0 ] && !LicenseKeyBits.Contains ( true ) )
            {
                LinkButton btnCreate = new LinkButton ( );
                btnCreate.Text = "Create a new Project";
                btnCreate.Attributes.Add ( "class", "icon-add" );
                btnCreate.Click += new EventHandler ( btnCreate_Click );
                NavigationSub.Commands.Add ( btnCreate );
            }
        }

        protected void btnCreate_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( ServerRelativeUrl + Constants.PortalFileUrls.ProjectNew );
        }

        protected void btnDelete_Click ( object sender, EventArgs e )
        {
            LinkButton btnDelete = ( LinkButton ) sender;
            int projectId = int.Parse ( btnDelete.CommandArgument );

            Project project = ProjectsModel.GetProjectById ( projectId, SiteCollectionId, ServerRelativeUrl );

            if ( project != null )
            {
                project.EditType = EditType.Deleted;
                project.ModifiedBy = CurrentUser;
                project = ProjectsModel.Save ( project, SiteCollectionId, ServerRelativeUrl );

                if ( project == null )
                    Response.Redirect ( string.Format ( "{0}{1}", ServerRelativeUrl, Constants.PortalFileUrls.ProjectsClosed ) );
            }
        }

        protected void rptProject_ItemDataBound ( object source, RepeaterItemEventArgs e )
        {
            Project project = ( Project ) e.Item.DataItem;

            PermissionsModel.GetGlobalPermissionBitsForCurrentUser ( project, CurrentUser, SiteCollectionId, ServerRelativeUrl );

            HyperLink lnkProject = ( HyperLink ) e.Item.FindControl ( "lnkProject" );
            if ( lnkProject != null )
            {
                lnkProject.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( project.Title );
                lnkProject.NavigateUrl = project.ServerRelativeWebUrl;
            }

            Label lblStartDate = ( Label ) e.Item.FindControl ( "lblStartDate" );
            if ( lblStartDate != null )
            {
                lblStartDate.Text = FormattingHelpers.DateTimeToStringOrDashes ( project.StartDate );
            }

            Label lblEndDate = ( Label ) e.Item.FindControl ( "lblEndDate" );
            if ( lblEndDate != null )
            {
                lblEndDate.Text = FormattingHelpers.DateTimeToStringOrDashes ( project.EndDate );
            }

            if ( project != null && project.ProjectManagerIds.Count > 0 )
            {
                User projectManager = UserModel.GetUserById ( project.ProjectManagerIds [ 0 ], SiteCollectionId, ServerRelativeUrl );
                if ( projectManager != null )
                {
                    HyperLink lnkProjectManager = ( HyperLink ) e.Item.FindControl ( "lnkProjectManager" );
                    if ( lnkProjectManager != null )
                    {
                        lnkProjectManager.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( projectManager.FullName );
                        lnkProjectManager.NavigateUrl = String.Format ( "{0}{1}?id={2}",
                            ServerRelativeUrl, Constants.PortalFileUrls.UserDisplay, projectManager.SPUserId );
                    }
                }
            }

            HyperLink lnkEdit = ( HyperLink ) e.Item.FindControl ( "lnkEdit" );
            if ( lnkEdit != null && project.PermissionBitsProjects [ 2 ] && project.PermissionBitsTeams [ 2 ] )
            {
                lnkEdit.Visible = true;
                lnkEdit.NavigateUrl = String.Format ( "{0}{1}", project.ServerRelativeWebUrl, Constants.ProjectFileUrls.ProjectEdit );
            }

            LinkButton btnDelete = ( LinkButton ) e.Item.FindControl ( "btnDelete" );
            if ( btnDelete != null && project.PermissionBitsProjects [ 3 ] && project.PermissionBitsTeams [ 3 ] )
            {
                btnDelete.Visible = true;
                btnDelete.CommandArgument = project.Id.ToString ( );
            }
        }

        #endregion

        #region Pager Related Methods

        private void SortList ( )
        {
            titleSort.Visible = false;
            endSort.Visible = false;

            Literal sortText = titleSort;
            string sortTextTemplate = "<img src='/_layouts/images/Kiiro/icon-sort-{0}.gif' />";

            switch ( V2Pager.SortExpression )
            {
                case "EndDate":
                    sortText = endSort;
                    projects.Sort ( delegate ( Project p1, Project p2 ) { return p1.EndDate.CompareTo ( p2.EndDate ); } );
                    break;
                case "Title":
                default:
                    sortText = titleSort;
                    projects.Sort ( delegate ( Project p1, Project p2 ) { return p1.Title.CompareTo ( p2.Title ); } );
                    break;
            }

            sortText.Visible = true;

            if ( V2Pager.SortDirection == SortDirection.Ascending )
            {
                sortText.Text = string.Format ( sortTextTemplate, "asc" );
            }
            else
            {
                sortText.Text = string.Format ( sortTextTemplate, "desc" );
                projects.Reverse ( );
            }
        }

        private void RePopulatePage ( object sender, EventArgs e )
        {
            PopulatePage ( );
        }

        private void FilterRepopulate ( object sender, EventArgs e )
        {
            V2Pager.IsFilter = true;
            PopulatePage ( );
        }

        protected void SortBy_Click ( object sender, EventArgs e )
        {
            LinkButton link = ( LinkButton ) sender;
            if ( V2Pager.SortDirection == SortDirection.Ascending && V2Pager.SortExpression == link.CommandArgument )
                V2Pager.SortDirection = SortDirection.Descending;
            else
                V2Pager.SortDirection = SortDirection.Ascending;
            V2Pager.SortExpression = link.CommandArgument;
            V2Pager.IsSortClick = true;
            V2Pager.DisplayedCount = rptProject.Items.Count;

            PopulatePage ( );
        }

        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.PortalPages/Projects/ClosedProjects.aspx.cs $
 * 
 * 24    2/08/10 2:28p Camerons
 * 
 * 23    2/08/10 12:00p Camerons
 * 
 * 22    1/06/10 12:39p Camerons
 * 
 * 21    12/23/09 3:31p Stefanf
 * 
 * 20    12/07/09 3:16p Stefanf
 * 
 * 19    12/02/09 12:29p Stefanf
 * 
 * 18    10/26/09 9:55a Adamw
 * Case 348
 * 
 * 17    8/10/09 6:30p Shafia
 * 
 * 16    7/10/09 5:23p Camerons
 * Case #285: Visibility for Delete link should default to hidden
 * 
 * 15    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 14    25/09/09 10:44a Shafia
 * fixed sort method to retain page index and display correct number of
 * rows when sort is clicked.
 * 
 * 13    23/09/09 4:34p Shafia
 * implemented the new WelcomeMessagePanel user control on Projects,
 * Users, CustomLists, Work, Documents, and Discussions pages.
 * Links are being displayed based on PermissionsBits[Entity]
 * 
 * 12    23/09/09 12:24p Shafia
 * 
 * 11    21/09/09 12:42p Shafia
 * 
 * 10    18/09/09 2:33p Shafia
 * New Pager Implemented. All data binding is done on the page itself not
 * on the Pager control
 * 
 * 9     18/09/09 1:21p Camerons
 * 
 * 8     16/09/09 10:19a Shafia
 * implemented the new pager
 * 
 * 7     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/